package com.ryder.wx.controller;

import com.ryder.wx.handler.WxChatMsgFactory;
import com.ryder.wx.handler.WxChatMsgHandler;
import com.ryder.wx.utils.MessageUtil;
import com.ryder.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

/**
 * 描述:
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0 // 版本号，指明从哪个版本开始
 * 更新日期: 2025/02/24
 */
@RestController
@Slf4j
public class CallBackController {

    private static final String TOKEN = "wxryder";

    @Autowired
    private WxChatMsgFactory wxChatMsgFactory;

    @RequestMapping("/test")
    public String test() {
        return "test ryder";
    }

    /**
     * 回调消息校验
     */
    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}, timestamp:{}, nonce:{}, echostr:{}",
                signature, timestamp, nonce, echostr);
        //将三个参数字符串拼接成一个字符串进行sha1加密
        String shaStr = SHA1.getSHA1(TOKEN, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknown";
    }

    //因为接收的xml格式的数据，所以要设置produces
    //样式地址：https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(@RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到微信的请求：requestBody:{}, signature:{}, timestamp:{}, nonce:{}, msg_signature:{}",
                requestBody, signature, timestamp, nonce);

        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);
        String msgType = msgMap.get("MsgType");
        // 如果Event等于空，则为普通消息，否则为事件推送
        String event = msgMap.get("Event") == null ? "" : msgMap.get("Event");
        log.info("msgType:{}, event:{}", msgType, event);
        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        // 如果消息类型为事件推送，则添加事件类型，否则为空 会报错
        if (!event.isEmpty()) {
            sb.append(".").append(event);
        }
        // 根据消息类型获取对应的处理类
        String msgTypeKey = sb.toString();
        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(wxChatMsgHandler)) {
            return "unknown";
        }
        String replyMessage = wxChatMsgHandler.dealMsg(msgMap);
        log.info("replyMessage:{}", replyMessage);
        return replyMessage;
    }

}
